package org.fuys.coder.domain.auth.service.vertify.permission.executor;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.fuys.coder.common.exception.vertify.PermissionException;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.fuys.coder.domain.auth.model.annotation.PermissionCertify;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.auth.service.vertify.permission
 * @className: PermissionCertifyAOP
 * @author: WangJing
 * @description: 执行增强类
 * @date: 2024/7/11 0:08
 * @version: 1.0
 */
@Aspect
@Component
public class PermissionCertifyAOP {

    @Resource
    private HttpServletRequest request;

//    @Resource
//    private RedisUtil redisUtil;

    private final Map<String,IPermissionCertifyExecutor> executorMap;

    @Autowired
    public PermissionCertifyAOP(ListableBeanFactory beanFactory) throws Exception {
        executorMap=beanFactory.getBeansOfType(IPermissionCertifyExecutor.class);
        if(ObjectUtils.isEmpty(executorMap)){
            throw new Exception("无法获取到处理权限验证的实现类 为了安全 将停止运行");
        }
    }

    @Before("@annotation(permissionCertify)")
    public void beforeCertify(PermissionCertify permissionCertify){
        final String executor = permissionCertify.executor();
        final IPermissionCertifyExecutor executorImpl = executorMap.get(executor);
        final boolean verify = executorImpl.verify(request, permissionCertify.permission());
        if(!verify){
            throw new PermissionException("权限不足");
        }
    }
}
